<?php

namespace frontendw\controllers;

use yii\web\Controller;
use Yii;
use yii\helpers\ArrayHelper;
use common\models\User;
use common\components\MTools;
use yii\helpers\Json;
use common\components\OperateEvent;
use frontendw\models\WB_UserAccountHy;

/* use Yii;
  use frontendm\models\LoginForm;
  use frontendm\models\PasswordResetRequestForm;
  use frontendm\models\ResetPasswordForm;
  use frontendm\models\SignupForm;
  use yii\base\InvalidParamException;
  use yii\web\BadRequestHttpException;
  use yii\web\Controller;
  use yii\filters\VerbFilter;
  use yii\filters\AccessControl; */

/**
 * WeChatController controller
 */
class WechatController extends Controller {

    public $xmlResult;
    private $eventType; //事件类型
    private $eventKey; //事件唯一标识
    private $msgType; //请求类型
    private $openid;
    private $msgContent;
    private $cacheTime = 360;

    /*
     * 获取微信请求相关信息
     */

    protected function initConfigInfo() {
        $this->msgType = ArrayHelper::getValue($this->xmlResult, "MsgType");
        $this->eventType = ArrayHelper::getValue($this->xmlResult, "Event");
        $this->eventKey = ArrayHelper::getValue($this->xmlResult, "EventKey");
        $this->openid = ArrayHelper::getValue($this->xmlResult, "FromUserName");
        $this->msgContent = ArrayHelper::getValue($this->xmlResult, "Content");
    }

    /*
     * 菜单点击操作
     */

    protected function clickMenuOperate() {
        switch ($this->eventKey) {
            //点击客服事件处理
            case "kefu":
                $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                $this->replayTextMessage($content);
                break;
            //点击提交任务
            case "PIC_000":
                //获取要提交的任务信息
                $taskModel = \frontendw\models\WB_UserTaskOperate::getWXCansubmitOneOfTask($this->openid);
                if ($taskModel) {
                    //缓存记录提交任务的ID
                    \yii::$app->cache->set($this->openid . "_taskid", $taskModel["id"] . "_" . $taskModel["taskid"] . "_" . $taskModel["sample_figure_count"], $this->cacheTime);
                    //模板带图片，链接提示
                    $data = [
                        'touser' => $this->openid,
                        'msgtype' => 'news',
                        'news' => [
                            'articles' => [
                                [
                                    'description' => '请您查看任务图片，是否您要提交的任务，直接在公众号传入图片即可完成任务',
                                    'url' => \yii\helpers\Url::toRoute(["task/taskdetail", "taskid" => $taskModel["taskid"], "id" => $taskModel["id"]], true),
                                    'picurl' => MTools::getQiniuImagepath($taskModel["sample_figure"])
                                ]
                            ]
                        ]
                    ];
                    Yii::$app->wechat->sendMessage($data);
                } else {
                    $content = '你当前没有正在进行的任务。点击菜单【首页】进入接新的任务吧！';
                    $this->replayTextMessage($content);
                }
                break;
            case "PIC_002":
                //获取要提交的任务ID
                $taskstring = \yii::$app->cache->get($this->openid . "_taskid");
                if ($taskstring) {
                    list($operid, $taskid, $sample_figure_count) = explode("_", $taskstring);
                    \yii::$app->cache->delete($this->openid . "_image_" . $taskid);
                    $content = '图片重置成功';
                } else {
                    $content = "你当前没有正在进行的任务。点击菜单【首页】进入接新的任务吧！";
                }
                $this->replayTextMessage($content);
            default:
                break;
        }
    }

    /*
     * 关注公众号，自动创建账号
     */

    protected function subscribeRem() {
        $userModel = User::find()->where("wxopenid=:wxopenid", [":wxopenid" => $this->openid])->one();
        if (!$userModel) {
            list($prefix, $store_id) = explode('_', $this->xmlResult->EventKey);
            $invite_code = "Y55970";
            if ($prefix === "qrscene" && !empty($store_id)) {
                //获取推荐人的信息
                $referModel = User::findOne($store_id);
                if ($referModel->froststatus == 0) {
                    $invite_code = $referModel->my_code;
                }
            }
            $trans = Yii::$app->db->beginTransaction();
            try {

                //获取微信信息
                $openInfo = Yii::$app->wechat->getUserInfo($this->openid);
                $user = new User();
                $user->username = $openInfo["nickname"];
                $user->role = 2;
                $user->my_code = MTools::makeOnlyNumber();
                $user->wxopenid = $this->openid;
                $user->setPassword(111111);
                $user->generateAuthKey();
                $user->generatePasswordResetToken();
                if ($user->save()) {
                    //保存基本信息
                    $userprofile = new \common\models\UserProfile();
                    $userprofile->userid = $user->id;
                    $userprofile->username = $user->username;
                    $userprofile->invite_code = $invite_code;
                    $userprofile->truename = $user->username;
                    $userprofile->headerimg = $openInfo["headimgurl"];
                    if ($userprofile->save()) {
                        $useraccount = new \common\models\UserAccountHy();
                        $useraccount->userid = $userprofile->userid;
                        $useraccount->amount = 0;
                        $useraccount->offline_amount = 0;
                        if ($useraccount->save()) {
                            $trans->commit();
                        }
                    }
                }
            } catch (Exception $ex) {
                $trans->rollBack();
                throw new \yii\web\NotFoundHttpException($ex);
            }
        }
    }

    /*
     * 微信发送消息的链接地址
     */

    public function actionValid() {
        $wechat = Yii::$app->wechat;
        $this->xmlResult = $wechat->parseRequestXml();
        if ($this->xmlResult) {
            $this->initConfigInfo();
            //判断请求的是否为事件
            if ($this->msgType == 'event') {
                //判断事件类型
                switch ($this->eventType) {
                    //关注处理
                    case 'subscribe':
                        $this->subscribeRem();
                        $content = "欢迎关注皓夜科技！\n";
                        $this->replayTextMessage($content);
                        break;
                    //click点击事件
                    case 'CLICK':
                        $this->clickMenuOperate();
                        break;
                    default:
                        break;
                }
            } else {
                $this->NotEventReplay();
            }
        }
    }

    /*
     * 被动回复文本消息
     * @params $content
     */

    private function replayTextMessage($content) {
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>";
        $resultStr = sprintf($textTpl, ArrayHelper::getValue($this->xmlResult, "FromUserName"), ArrayHelper::getValue($this->xmlResult, "ToUserName"), time(), "text", $content);
        echo $resultStr;
    }

    /*
     * 被动消息回复，非事件
     */

    private function NotEventReplay() {
        $replayResult = explode("@", $this->msgContent);
        $argcount = count($replayResult);
        if ($argcount > 2) {
            $this->replayTextMessage($this->msgContent);
            $username = substr(substr($this->msgContent, 0, strrpos($this->msgContent, "@")), strpos($this->msgContent, "@") + 1);
            $bd = $replayResult[0];
            $password = $replayResult[$argcount - 1];
            if ($bd == "bd") {
                //微信绑定账号
                $content = $this->userBindOpenID($username, $password);
            } else {
                $content = "亲，请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
            }
        } else if ($this->msgType == 'image') {
            //获取要提交的任务ID
            $taskstring = \yii::$app->cache->get($this->openid . "_taskid");
            if ($taskstring) {
                list($operid, $taskid, $sample_figure_count) = explode("_", $taskstring);
                $mediald = ArrayHelper::getValue($this->xmlResult, "MediaId");
                $result = Yii::$app->wechat->getMedia($mediald);
                if ($result) {
                    //查询缓存
                    $cache_task_image = \yii::$app->cache->get($this->openid . "_image_" . $taskid);
                    if (!$cache_task_image) {
                        $cache_task_image = [];
                    }
                    array_push($cache_task_image, $result);
//                    //加入缓存
                    \yii::$app->cache->set($this->openid . "_image_" . $taskid, $cache_task_image, $this->cacheTime);
////                    //判断会员是否已经上传足够的任务图片
                    $num = $sample_figure_count - count($cache_task_image);
                    if ($num == 0) {
                        //提交任务
                        $OperateEvent = new OperateEvent();
                        $content = $OperateEvent->completeTasks($cache_task_image, $operid);
                        //上传完成删除值
                        \yii::$app->cache->delete($this->openid . "_taskid");
                        \yii::$app->cache->delete($this->openid . "_image_" . $taskid);
                    } else {
                        $content = "亲，需要上传".$sample_figure_count."张图，您还差".$num."张图未上传无法提交！";
                        
                    }
                } else {
                    $content = "提取图片失败";
                }
            } else {
                $content = "您发了张图片，可是我不明白是什么意思。如果您是想提交任务截图，请先点击下方的【交任务】菜单【提交任务】，再提交截图哦！";
            }
        }
        $this->replayTextMessage($content);
    }

    /*
     * 微信绑定账号
     * @params $username
     * @params  $password
     */

    protected function userBindOpenID($username, $password) {
        if ($username && $password) {
            $useropen = User::find()->where("wxopenid=:wxopenid and role=2", [":wxopenid" => $this->openid])->one();
            if (!$useropen instanceof User) {
                $user = User::find()->where("username=:username and role=2", [":username" => $username])->one();
                if ($user instanceof User) {
                    if ($user->validatePassword($password)) {
                        if ($user->wxopenid) {
                            $content = "您输入的帐号已绑定过了：" . $username;
                        } else {
                            $user->wxopenid = $this->openid;
                            if ($user->save()) {
                                $content = "已经成功为你绑定帐号[" . $user->username . "]。点击下方菜单，开始体验吧！";
                            } else {
                                $content = "对不起，您绑定失败";
                            }
                        }
                    } else {
                        $content = "对不起，您输入的账号或密码不正确";
                    }
                } else {
                    $content = "对不起，您输入的账号不存在";
                }
            } else {
                $content = "此微信号已绑定过帐号" . $useropen->username; //"亲。您已经绑定了".."账号。一个微信号只能绑定一个平台账号！";
            }
        } else {
            $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
        }
        return $content;
    }

    /*
     * 创建菜单
     */

    public function actionCreatemenu() {
        $buttons = [
            [
                'name' => '交任务',
                'sub_button' => [
                    [
                        "type" => "click",
                        "name" => "提交任务",
                        "key" => "PIC_000"
                    ],
                    [
                        "type" => "click",
                        "name" => "重新提交",
                        "key" => "PIC_002"
                    ]
                ]
            ],
            [
                'name' => '首页',
                "type" => "view",
                "url" => \yii\helpers\Url::toRoute(["site/index"], true),
            ],
            [
                'name' => '个人中心',
                'sub_button' => [
                    [
                        "type" => "view",
                        "name" => "个人信息",
                        "url" => \yii\helpers\Url::toRoute(["profile/info"], true),
                    ],
                    [
                        "type" => "click",
                        "name" => "客服中心",
                        "key" => "kefu"
                    ]
                ]
            ]
        ];
        $result = Yii::$app->wechat->createMenu($buttons);
        if ($result) {
            echo "创建菜单成功";
        }
    }

    public function actionTuisong() {

        $urlx = 'http://wx.toupiao518.com/wechat/tuisong.html';
        if ($code = Yii::$app->request->get("code")) {
            $openid_info = Yii::$app->wechat->getOauth2AccessToken($code);
//                $data = [
//                    'touser'=>$openid_info['openid'],
//                    'msgtype'=>'text',
//                    'text'=>["content'=>'hello world <a href='http://www.baidu.com'>点击查看详情</a>"]
//                ];
            $data = [
                'touser' => $openid_info['openid'],
                'msgtype' => 'news',
                'news' => [
                    'articles' => [
                        [
                            'title' => '标题',
                            'description' => '内容',
                            'url' => 'http://www.baidu.com',
                            'picurl' => 'http://www.hishop.com.cn/uploads/150914/21678-150914112244436.jpg'
                        ]
                    ]
                ]
            ];

            $result = Yii::$app->wechat->sendMessage($data);
            var_dump($result);
            die;
            if ($result)
                echo '成功';
        } else {
            $url = Yii::$app->wechat->getOauth2AuthorizeUrl($urlx);
            header("Location:$url");
        }
    }

}
